package com.sjh;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author jack
 * @data 2020/9/3 3:23 下午
 */
public class CacheDemo {
    private Map<String, Object> cache = new HashMap<>();

    public static void main(String[] args) {

    }
    private ReadWriteLock wrLock = new ReentrantReadWriteLock();

    public Object getData(String key) {
        wrLock.readLock().lock();
        Object value;
        try {
            value = cache.get(key);
            if (value == null) {
                wrLock.readLock().unlock();
                wrLock.writeLock().lock();
                // 实际操作数据库获取
                try {
                    // 防止多个线程执行写操作
                    if (value == null) {
                        value = "set value";
                    }
                } finally {
                    wrLock.writeLock().unlock();
                    wrLock.readLock().lock();
                }
            }
        } finally {
            wrLock.readLock().unlock();
        }

        return value;
    }
}
